package com.deer.wms.base.system.web;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.base.system.model.Cell.CellInfo;
import com.deer.wms.base.system.model.Cell.CellInfoCriteria;
import com.deer.wms.base.system.model.Cell.CellInfoDto;
import com.deer.wms.base.system.service.CellInfoService;
import com.deer.wms.busine.tactic.model.PrintTempInfo;
import com.deer.wms.busine.tactic.service.PrintTempInfoService;
import com.deer.wms.busine.tactic.service.PrintTempUtils;
import com.deer.wms.intercept.annotation.Authority;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.constant.Constants;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.system.manage.service.CellLedService;
import com.deer.wms.system.manage.test.CellLedCriteria;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.stream.Collectors;

/**
* Created by guo on 2019/11/27.
*/
@Api(description = "货位信息api接口")
@RestController
@RequestMapping("/cell/infos")
public class CellInfoController {

    @Autowired
    private CellInfoService cellInfoService;

    @ApiOperation(value = "新增货位信息", notes = "新增货位信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/insert")
    public Result add(@RequestBody CellInfo cellInfo, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        cellInfoService.save(cellInfo);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        cellInfoService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody CellInfo cellInfo) {
        cellInfoService.updateById(cellInfo);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(Integer id) {
        CellInfo cellInfo = cellInfoService.getById(id);
        return ResultGenerator.genSuccessResult(cellInfo);
    }

    @ApiOperation(value = "通过库位编码及仓库ID查询库位信息", notes = "通过库位编码及仓库ID查询库位信息")
    @GetMapping("/getCellByCode")
    public Result getCellByCode(String code, Integer wareId) {
        CellInfoDto cellInfo = cellInfoService.findByCodeAndWareId(code, wareId);
        return ResultGenerator.genSuccessResult(cellInfo);
    }

    @GetMapping("/list")
    public Result list(CellInfoCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<CellInfoDto> list = cellInfoService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    /**
     * 通过仓库id查找下的货位列表
     * @param 
     * @return
     */
    @GetMapping("/cellByWareIdlist")
    public Result cellByWareIdlist(CellInfoCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<CellInfoDto> list = cellInfoService.findByWareIdList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/findByShelfInfoId")
    public Result findByShelfInfoId(Integer shelfInfoId) {
        List<CellInfo> list = cellInfoService.findByShelfInfoId(shelfInfoId);
        return ResultGenerator.genSuccessResult(list);
    }

    @GetMapping("/findByCellUserTypes")
    public Result findByCellUserTypes(CellInfoCriteria criteria) {
        List<CellInfoDto> list = cellInfoService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    /**
     * 启用货位
     *
     * @param cellCode
     * @return
     */
    @ApiOperation(value = "启用货位", notes = "启用货位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType="header", dataType="String", dataTypeClass = String.class, required = true)
    })
    @Authority
    @GetMapping("/enable")
    public Result enable(String cellCode,Integer wareId, @ApiIgnore @User CurrentUser currentUser) {

        cellInfoService.modifyCellState(cellCode, wareId,Constants.CELL_ENABLE, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 停用货位
     *
     * @param cellCode
     * @return
     */
    @ApiOperation(value = "停用货位", notes = "停用货位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType="header", dataType="String", dataTypeClass = String.class, required = true)
    })
    @Authority
    @GetMapping("/disable")
    public Result disable(String cellCode,Integer wareId,@ApiIgnore @User CurrentUser currentUser) {

        cellInfoService.modifyCellState(cellCode, wareId,Constants.CELL_DISABLE, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @Autowired
    private PrintTempInfoService printTempInfoService;

    /**
     * 打印
     *
     * @param cellCode
     * @return
     */
    @ApiOperation(value = "打印", notes = "打印")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType="header", dataType="String", dataTypeClass = String.class, required = true)
    })
    @Authority
    @GetMapping("/print")
    public Result print(String cellCode,Integer wareId,@ApiIgnore @User CurrentUser currentUser) {


        CellInfoDto cellInfoDto = cellInfoService.findByCodeAndWareId(cellCode,wareId);


        PrintTempInfo printTempInfo = printTempInfoService.findByWare(wareId,"货位标签");
        if(printTempInfo==null){
            throw  new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"未匹配到货位标签模板");
        }
        String html = printTempInfo.getTempHtml();
        Document doc = Jsoup.parse(html);
        //删除不显示的
        doc.select(".dis-none").remove();
        //直线中间蓝点的问题
        doc.select(".line-handle").remove();


        PrintTempUtils.setTempData("WARE_CODE",cellInfoDto.getWareCode(),doc,"text");
        PrintTempUtils.setTempData("WARE_NAME",cellInfoDto.getWareName(),doc,"text");

        PrintTempUtils.setTempData("AREA_NAME",cellInfoDto.getAreaName(),doc,"text");
        PrintTempUtils.setTempData("AREA_CODE",cellInfoDto.getAreaCode(),doc,"text");


        PrintTempUtils.setTempData("CELL_CODE",cellInfoDto.getCellCode(),doc,"text");
        PrintTempUtils.setTempData("CELL_CODE_QR_CODE",cellInfoDto.getCellCode(),doc,"qrCode");
        PrintTempUtils.setTempData("CELL_CODE_BAR_CODE",cellInfoDto.getCellCode(),doc,"barCode");

        PrintTempUtils.setTempData("SHELF_CODE",cellInfoDto.getShelfCode(),doc,"text");
        PrintTempUtils.setTempData("SHELF_CODE_QR_CODE",cellInfoDto.getShelfCode(),doc,"qrCode");
        PrintTempUtils.setTempData("SHELF_CODE_BAR_CODE",cellInfoDto.getShelfCode(),doc,"barCode");





        //doc在创建时里面包含了html head body等节点  不需要
        Element labelContent = doc.getElementsByAttributeValue("class","label-content").get(0);
        String tempHtml = labelContent.toString();


        return ResultGenerator.genSuccessResult(tempHtml);
    }

    @Autowired
    private CellLedService cellLedService;

    @ApiOperation(value = "卓品电子料架", notes = "")
    @PostMapping("/operate")
    public Result operate(@RequestBody CellLedCriteria cellLedBo, @ApiIgnore @User CurrentUser currentUser) {
        for (String cellCode : cellLedBo.getCellCodes()) {
            CellInfo cellInfo = cellInfoService.getOneByField("cell_code", cellCode);
            if (ObjectUtil.isNull(cellInfo)) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "[" + cellCode + "]不为库位编码，请确认！");
            }
        }

        cellLedService.ledControl(cellLedBo.getCellCodes(), cellLedBo.getColor(), cellLedBo.getTime(), cellLedBo.getLighttype());

        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "卓品电子料架", notes = "")
    @PostMapping("/operate/allOff")
    public Result operateAllOff(@ApiIgnore @User CurrentUser currentUser) {
        QueryWrapper<CellInfo> qw = new QueryWrapper<>();
        List<CellInfo> cellInfos = cellInfoService.list(qw.likeRight("cell_code", "2"));
        List<String> collect = cellInfos.stream().map(CellInfo::getCellCode).collect(Collectors.toList());
        cellLedService.ledControl(collect, null, null, 0);
        return ResultGenerator.genSuccessResult();
    }
}
